package com.jason.lucene.example.search;

import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.junit.Assert;
import org.junit.Test;

/**
 * 模糊查询测试 , FuzzyQuery 会尽可能的枚举出一个索引中的所有项。最好少使用这类查询。
 *
 * @author he peng
 * @create 2017/12/6 19:05
 * @see
 */
public class FuzzyQueryTest extends BaseQueryTest {


    @Test
    public void testFuzzy() throws Exception {
        indexingSingleFieldDocs(new Field[]{
                new Field("contents" , "fuzzy" , TextField.TYPE_STORED) ,
                new Field("contents" , "wuzzy" , TextField.TYPE_STORED) ,
        });

        String text = "wuzza";
        Query fuzzyQuery = new FuzzyQuery(new Term("contents" , text));
        System.err.println("query =====> " + fuzzyQuery);
        IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(this.dir));
        TopDocs topDocs = searcher.search(fuzzyQuery, 1000);
        for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
            System.err.println("hit doc =====> " + searcher.doc(scoreDoc.doc));
        }

        Assert.assertEquals("both close enough" , 2 , topDocs.scoreDocs.length);
        Assert.assertTrue("wuzzy closer than fuzzy" ,
                    topDocs.scoreDocs[0].score != topDocs.scoreDocs[1].score);
        Assert.assertEquals(
                    text + " bear" , "wuzzy" ,
                searcher.doc(topDocs.scoreDocs[0].doc).get("contents"));
    }
}
